//
//  GBJobTableView.m
//  警用舆情平台
//
//  Created by 郭斌 on 15/6/19.
//  Copyright (c) 2015年 魏强. All rights reserved.
//

#import "GBJobTableView.h"
#import "GBRequest.h"
#import "MJRefresh.h"
#import "Cell5_2.h"
#import "GBModel.h"
#import "UIImageView+WebCache.h"
#import "GBSingleWebViewController.h"
#import "Reachability.h"
#import "JobSingleViewController.h"

@interface GBJobTableView () <UITableViewDataSource,UITableViewDelegate,GBRequestDelegate>
{
    //4.16改
    NSString *refreshUrl; //下拉加载更多的url

}

@end

@implementation GBJobTableView

#pragma mark - 实例化方法
-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self)
    {
//        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.7 target:self selector:@selector(lateeeee) userInfo:nil repeats:NO];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self lateeeee];
        });
        //初始化
        self.data = [NSMutableArray array];
        self.backgroundColor = WQColor(241, 243, 244);
        //_url = [NSString string];
        self.rowHeight = 69;
        self.tableFooterView = [[UIView alloc] init];
        self.delegate = self;
        self.dataSource = self;
        [self registerClass:[Cell5_2 class] forCellReuseIdentifier:@"Cell5_2"];
        //去掉下划线
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return self;
}

#pragma mark - 延时
-(void)lateeeee
{
//    __weak typeof(self) weakSelf = self;
    
    // 添加传统的下拉刷新
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(startRequest)];
    
    // 马上进入刷新状态
    [self.header beginRefreshing];
    
    // 添加传统的上拉刷新
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    //[self addLegendFooterWithRefreshingBlock:^{
    //    [weakSelf loadMoreData];
    //}];
    /**
     也可以这样使用
     [self.tableView.header beginRefreshing];
     此时self.tableView.header == self.tableView.legendHeader
     */
}

#pragma mark - 开始请求数据
-(void)startRequest
{
    //检查当前网络状态
    
    //清空数组
    [self.data removeAllObjects];
    //NSLog(@"基本url:%@",_Jurl);
    GBRequest *request1 = [[GBRequest alloc]initWithUrlStr:_Jurl];
    //NSLog(@"tid = %@",_tidString);
    request1.tag = 1;
    request1.delegate = self;
    [request1 startRequestData];
}

#pragma mark - 数据成功请求完毕
- (void)requestDidFinished:(GBRequest *)request
{
    //NSLog(@"4");
    NSString *str = [[NSString alloc] initWithData:request.requestData encoding:NSUTF8StringEncoding];
    //解析
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    id dataArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSDictionary *jsonDict = nil;
    if ([dataArray isKindOfClass:[NSDictionary class]])
    {
        jsonDict = dataArray;
        //NSLog(@"%@",jsonDict[@"status"]);
    }
    
    NSMutableArray *info = jsonDict[@"task"];
    for(NSDictionary *dic in info)
    {
        GBModel *model = [[GBModel alloc] init];
        model.c_CreateName = dic[@"c_CreateName"];
        model.c_Name = dic[@"c_Name"];
        
        //NSLog(@"%@",dic[@"docId"]);
        model.t_Name = dic[@"t_Name"];
        id addtime = dic[@"t_AddTime"];
        model.fav_id = [addtime intValue];
        id lasttime = dic[@"d_LastTime"];
        model.d_LastTime = [lasttime intValue];
        id tid = dic[@"t_Id"];
        model.t_Id = [tid intValue];
        id type = dic[@"t_Type"];
        model.t_Type =[type intValue] ;//[NSString stringWithFormat:@"%d",[type intValue]]
        //NSLog(@"%d",model.t_Id);
        [self.data addObject:model];
    }
    [self reloadData];
    //停止更新数据
    [self.header endRefreshing];
    [self.footer endRefreshing];
    //NSLog(@"%@",self.data);
}

#pragma mark - 数据请求失败
- (void)requestDidFailedWithError:(NSError *)error
{
    UIAlertView *messageView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"数据请求失败，请检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [messageView show];
    
    //停止更新数据
    [self.header endRefreshing];
    [self.footer endRefreshing];
}

#pragma mark - tableview返回行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell5_2";
    Cell5_2 *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    if(self.data.count > 0)
    {
        GBModel *model = self.data[indexPath.row];
        cell.titleLabel1.text = model.t_Name;
        //cell.titleLabel1.font = [UIFont systemFontOfSize:19];
        cell.titleLabel1.font = [UIFont boldSystemFontOfSize:17];
        cell.titleLabel1.textColor = [UIColor colorWithRed:(64.0 / 255.0) green:(64.0 / 255.0) blue:(64.0 / 255.0) alpha:1];
        cell.titleLabel1.frame = CGRectMake(10, -8, self.frame.size.width - 20, 60);
        
        cell.timeLabel.text = [NSString stringWithFormat:@"%d",model.t_AddTime];
        cell.timeLabel.font = [UIFont systemFontOfSize:12];
        
        cell.lasttiemLabel.text = [NSString stringWithFormat:@"%d",model.d_LastTime];
        cell.lasttiemLabel.font = [UIFont systemFontOfSize:12];
        
        cell.comeFromLabel.text = model.c_Name;
        cell.comeFromLabel.font = [UIFont systemFontOfSize:12];
        
//        cell.typeLabel.text = model.t_Type;
        cell.typeLabel.font = [UIFont systemFontOfSize:12];
        //定制cell右按钮
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return cell;
}

//cell选中执行
#pragma mark - 当单元格被选中
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger count = self.data.count;
    //跳转单个信息
    JobSingleViewController *single = [[JobSingleViewController alloc] init];
    //NSLog(@"$$$");
    if(count != 0)
    {
        GBModel *model = self.data[indexPath.row];
        single.uid = [NSString stringWithFormat:@"%d",model.t_Id];
        single.jobName = model.t_Name;
        //NSLog(@"%d",model.u_id);
        NSDictionary *userInfo11b = [[NSDictionary alloc] initWithObjectsAndKeys:single.uid,@"singleUid",single.jobName,@"singleTname",nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"goToTheJobSingleView" object:nil userInfo:userInfo11b];
    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
